package com.kantboot.system.user.service.impl;

import com.kantboot.system.user.dao.repository.entity.SysUserRoleRepository;
import com.kantboot.system.user.domain.entity.SysUserRole;
import com.kantboot.system.user.exception.SystemUserException;
import com.kantboot.system.user.service.ISysUserRoleService;
import com.kantboot.system.user.service.IUserSelfService;
import jakarta.annotation.Resource;
import jakarta.persistence.Transient;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysUserRoleServiceImpl implements ISysUserRoleService {

    @Resource
    private SysUserRoleRepository repository;

    @Resource
    private IUserSelfService userSelfService;

    /**
     * 给用户添加角色
     */
    @Transient
    @Override
    public void addUserRole(Long userId, String roleCode) {
        SysUserRole byUserIdAndRoleCode = repository.findByUserIdAndRoleCode(userId, roleCode);
        if(byUserIdAndRoleCode != null){
            // 如果已经存在，抛出异常，提示用户已经有该角色
            throw SystemUserException.USER_ALREADY_HAVE_ROLE;
        }
        repository.save(new SysUserRole()
                .setUserId(userId)
                .setRoleCode(roleCode)
        );
    }

    @Override
    public List<String> getRoleCodeListByUserId(Long userId) {
        return repository.getRoleCodeListByUserId(userId);
    }

    /**
     * 获取用户自身的角色编码列表
     */
    @Override
    public List<String> getSelfRoleCodeList() {
        return getRoleCodeListByUserId(userSelfService.getSelfId());
    }
}
